$(function () {
    getCoachList();
})

function editTeam(data, index) {
    layui.use(['upload', 'form', 'laydate', 'layer'], function () { //此段代码必不可少
        var form = layui.form;
        var upload = layui.upload;
        var laydate = layui.laydate;
        laydate.render({
            elem: '#entranceTime'
        });
        //执行实例
        var uploadInst = upload.render({
            elem: '#icon_change', //绑定元素

            url: LOCALHOSTURL + '/user/upload', //上传接口

            accept: 'images',
            acceptMime: 'image/*',
            xhrFields: {
                withCredentials: true //默认情况下，标准的跨域请求是不会发送cookie的
            },
            headers: {
                "Authorization": $.cookie("token")
            },
            crossDomain: true,
            before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#icon').attr('src', result); //图片链接（base64）
                });
            },
            // done: function (res) {
            //上传完毕回调
            //     return layer.msg(res.message);
            // ("#icon").attr("src", res.iconName);
            // },
            error: function () {
                // 请求异常回调
                // 演示失败状态，并实现重传
                // var demoText = $('#demoText');
                // demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                // demoText.find('.demo-reload').on('click', function(){
                //     uploadInst.upload();
                // });
                // return layer.alert('上传失败');
            }
        });
        if (data == "") {
            $("#name").removeAttr("readonly");
            //将按钮改成添加
            $("#update").html("添加");
            $("#leader").attr("disabled", "disabled");
            $("#update").click(function () {
                let name = $("#name").val();
                let desc = $("#desc").val();
                let stage = $("#stage").val();
                if (name == '') {
                    layer.msg("组名不能为空", function () {
                        $("#name").focus();
                    })
                } else if (name != '') {
                    let result = myAjax("/team/team/getTeamByName", "get", {"name": name});
                    if (result.data == null) {
                        let teamdata = {
                            "name": name,
                            "description": desc,
                            "stage": stage,
                            "leader": $("#leader").find("option:selected").val(),
                            "coach": $("#coach").find("option:selected").val(),
                            "clazzRoom": $("#clazzRoom").val()
                        };
                        console.log(teamdata);
                        let result = ajaxModel("/team/team/addTeam", "post", teamdata);
                        if (result.code == 200) {
                            layer.alert(result.message, {icon: 1}, function () {
                                parent.location.reload();
                                parent.layer.close(index);
                            });
                        } else
                            layer.alert(result.message, {icon: 1});
                    }
                } else {
                    layer.msg("该组名已存在");
                    $("#name").focus();
                }
            });
            $("#cancel").click(function () {
                parent.layer.close(index);
            });
            form.render();
        } else {
            data = JSON.parse(data);
            //给表单赋值
            let teamMembers = myAjax("/user/user/getTeamMember", "get", {"teamId": data.id});
            let members = teamMembers.data;
            console.log(members);
            if (members == "[]")
                $("#leader").html("<option value=''>暂无</option>");
            else {
                $.each(members, function (i, member) {
                    if (member.name != null && member.name != '')
                        $("#leader").append("<option value='" + member.code + "'>" + member.code + "(" + member.name + ")" + "</option>");
                    else
                        $("#leader").append("<option value='" + member.code + "'>" + member.code + "</option>");
                })
            }

            $("#name").val(data.name);
            $("#name").attr("disabled", "disabled");
            $("#desc").val(data.description);
            $("#stage").val(data.stage);
            $("#clazzRoom").val(data.clazzRoom);
            $("#leader").find("option[value='" + data.leader + "']").prop("selected", "selected");
            let preLeader = $("#leader").find("option:selected").val();
            $("#coach").find("option[value='" + data.coach + "']").prop("selected", "selected");
            let leader = "";
            form.on("select(leader)", function () {
                leader = $("#leader").find("option:selected").val();
                console.log(leader);
            })
            $("#update").click(function () {
                let name = $("#name").val();
                let desc = $("#desc").val();
                let stage = $("#stage").val();
                let clazzRoom = $("#clazzRoom").val();
                if (leader != "") {
                    let res = myAjax("/user/userRole/changeLeader", "post", {preLeader: preLeader, leader: leader});
                    console.log(res.message);
                } else
                    leader = preLeader;
                let teamdata = {
                    "id": data.id,
                    "name": name,
                    "description": desc,
                    "stage": stage,
                    "clazzRoom": clazzRoom,
                    "leader": leader,
                    "coach": $("#coach").find("option:selected").val()
                };
                console.log(teamdata);
                let result = ajaxModel("/team/team/updateTeam", "post", teamdata);
                if (result.code == 200) {
                    layer.alert(result.message, {icon: 1}, function () {
                        parent.location.reload();
                        parent.layer.close(index);
                    });
                } else {
                    layer.alert(result.message, {icon: 1});
                }
            });
            $("#cancel").click(function () {
                parent.layer.close(index);
            });
            form.render();
        }
    });
}

function getCoachList() {
    let coaches = myAjax("/user/user/getCoachList", "get");
    let coachs = coaches.data;
    if (coachs == "[]")
        $("#coach").html("<option value=''>暂无</option>");
    else {
        $.each(coachs, function (i, coach) {
            if (coach.name != null && coach.name != '')
                $("#coach").append("<option value='" + coach.code + "'>" + coach.code + "(" + coach.name + ")" + "</option>");
            else
                $("#coach").append("<option value='" + coach.code + "'>" + coach.code + "</option>");
        })
    }
}
